import { Component, OnInit } from '@angular/core';
import {SinglePage} from "../../model/SinglePage";
import {SinglepageeditComponent} from "../singlepageedit/singlepageedit.component";
import {SinglepageService} from "../../service/singlepage.service";
import {DialogService} from "primeng/api";

@Component({
  selector: 'app-singlepageadmin',
  templateUrl: './singlepageadmin.component.html',
  styleUrls: ['./singlepageadmin.component.css']
})
export class SinglepageadminComponent implements OnInit {
  sl:Array<SinglePage>
  constructor(private singlepageservice:SinglepageService
    ,private dialogService: DialogService) {
    this.sl=new Array();

  }

  ngOnInit() {
    this.loadSinglePageList();

  }


  //从服务器端获取单页列表数据
  loadSinglePageList(){
    this.singlepageservice.getSinglePageList()
      .then((data:any)=>{
        this.sl=new Array();
        this.sl=data;


      })


  }

  add(){
    //弹出编辑窗口
    const ref = this.dialogService.open(SinglepageeditComponent, {
      header: '添加单页'

    });

    //订阅窗口关闭事件

    ref.onClose.subscribe((singlepage: SinglePage) => {
      if (singlepage) {
        //保存数据到服务器
        this.singlepageservice.saveSinglePage(singlepage)
          .then((data:any)=>{
            if(data.msg=='ok'){
              this.loadSinglePageList();
            }
            else{
              //提示错误
            }


          })




      }
    });



  }

  //删除

  delete(id:string){

    this.singlepageservice.deleteSinglePage(id)
      .then((data:any)=>{
        if(data.msg=='ok'){
          this.loadSinglePageList();
        }
        else{
          //弹出错误信息;
        }


      })


  }

  update(id:string){
    //从服务器端读取数据
    this.singlepageservice.getSinglePageById(id)
      .then((data:any)=>{
        if(data){
          let singlepage:SinglePage;
          singlepage=new SinglePage();
          singlepage=data;

          //发送要编辑的数据到编辑窗口
          //弹出编辑窗口
          const ref = this.dialogService.open(SinglepageeditComponent, {
            header: '修改单页',
            data:{
              "singlepage":singlepage
            }

          });

          //订阅窗口关闭事件

          ref.onClose.subscribe((singlepage: SinglePage) => {
            if (singlepage) {
              //保存数据到服务器
              this.singlepageservice.saveSinglePage(singlepage)
                .then((data:any)=>{
                  if(data.msg=='ok'){
                    this.loadSinglePageList();
                  }
                  else{
                    //提示错误
                  }


                })




            }
          });


        }


      });




  }



}
